<?php

namespace app\data\command;

use app\mall\logic\orderLogic;
use app\mall_back\model\GoodsLuckyDrawModel;
use think\admin\Command;
use think\admin\Exception;
use think\console\Input;
use think\console\Output;

class DelayDrawRunning extends Command
{
    protected function configure()
    {
        $this->setName('delay-draw:running');
        $this->setDescription('延时开奖命令');

        return $this;
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $startTime = microtime(true);
        while(time() - $startTime < 55) {
            $draws = GoodsLuckyDrawModel::where('status', GoodsLuckyDrawModel::STATE_DRAWING)
                ->field('id, draw_delay, win_time, create_time, status')
                ->where('draw_delay', '>', 0)
                ->limit(10)
                ->select();

            $min_sleep = 60 - (time() - $startTime);
            foreach ($draws as $item) {
                //   开奖 + 延时 大于
                if (strtotime($item->win_time) + $item->draw_delay * 60 <= time()) {
                    $item->draw_delay = 0;
                    $item->save();
                    orderLogic::run_lottery($item->id);
                    $output->info("【信息】执行开奖" . $item->id . PHP_EOL);
                } else {
                    $diff_t = strtotime($item->win_time) + $item->draw_delay * 60 - time();
                    if ($diff_t < $min_sleep) {
                        $min_sleep = $diff_t;
                    }
                    $output->info("【调试】抽奖 [{$item->id}] 还需要 {$diff_t} 秒, 才开奖..");
                }
            }

            $output->info("【调试】休眠 {$min_sleep} 秒..");
            sleep($min_sleep);
        }
    }
}
